<template>
  <div id="Shelf">
    <div class="filter-box">
      <div class="top-box">
        <Filters
          :form="searchForm"
          :filterData="filterData"
          @confirm="changePage(1)"
        />
      </div>
    </div>
    <div class="container">
      <div class="order-table">
        <a-row class="table-header">
          <a-col :span="8">商品</a-col>
          <a-col :span="4">预订单价</a-col>
          <a-col :span="4">预订数量</a-col>
          <a-col :span="4">确认收货数量</a-col>
          <a-col :span="4">待确认收货数量</a-col>
        </a-row>
        <div class="search">
          <Sort @change="changeSort"/>
          状态：
          <a-select
            v-model="searchForm.status"
            @change="getList"
            placeholder="请选择"
            size="small"
            allowClear
            class="search-selsect"
          >
            <a-select-option
                v-for="option in statusList"
                :key="option.value"
                :value="option.value">
                {{option.label}}
          </a-select-option>
          </a-select>
        </div>
        <div
          class="table-item"
          v-for="(item, index) in Data"
          :key="index"
        >
          <a-row class="table-item-desc" type="flex" >
            <a-col :span='6'>订单编号：<b>{{ item.shopOrderSn }}</b></a-col>
            <a-col :span='4'>订单合计：￥{{ item.orderTotal }}</a-col>
            <a-col :span='4' class="item-orderStatus">订单状态：{{ switchStatus(item.orderStatus) }}</a-col>
            <a-col class="item-btn" :span='10'>
              <a-button  size="small" class="btns" v-if="['YFH'].includes(item.orderStatus) && item.shopOrders.find(i=>{ return i.sendNum===0}) && item.needRec===0" @click="overHandle(item.shopOrderTitleId)">结束订单</a-button>
              <a-button  size="small" class="btns" v-if="['YQX'].includes(item.orderStatus)" @click="delHandle(item.shopOrderTitleId)">删除订单</a-button>
              <a-button  size="small" class="btns" v-if="['DFH'].includes(item.orderStatus)" @click="cancelHandle(item.shopOrderTitleId)">取消订单</a-button>
              <a-button  size="small" class="btns" @click="$router.push({path:'/allot/myPurchase/detail', query:{shopOrderTitleId:item.shopOrderTitleId}})">订单详情</a-button>
                <a-button type="primary" class="btns" size="small" v-if="item.needRec===1"  @click="$router.push({path:'/allot/myPurchase/operate', query:{shopOrderTitleId:item.shopOrderTitleId}})">确认收货</a-button>
                <!-- ['YFH'].includes(item.orderStatus) &&  -->
            </a-col>
          </a-row>
          <a-row class="table-item-body" v-for="i in item.shopOrders" :key="i.orderId">
            <a-col :span="8" class="flex-row">
              <img :src="i.goodsPic" class="table-pic" />
              <div class="table-info">
                <p class="info-name-new" >{{ i.ncMaterielName }}</p>
                <p>规格：{{ i.goodsSpec }}</p>
                <p>单位：{{ i.goodsUnit }}</p>
              </div>
            </a-col>
            <a-col :span="4" class="item-col">
              ￥{{ i.buyPrice }}
            </a-col>
            <a-col :span="4" class="item-col">
              {{ i.number }}
            </a-col>
            <a-col :span="4" class="item-col">
              {{ i.recNum }}
            </a-col>
            <a-col :span="4" class="item-col">
              {{ i.keRecNum}}
            </a-col>
          </a-row>
        </div>
        <div class="table-empty" v-if="!Data.length">
          <img src="@/assets/images/empty.png" />
          <span>暂无数据</span>
        </div>
      </div>
      <div class="page-box">
        <a-pagination
          size="small"
          :total="pageConfig.total"
          show-quick-jumper
          :show-total="(total) => `总共 ${pageConfig.total} 条数据`"
          @change="changePage"
        />
      </div>
      <CommonDialog
        :rows="order.rows"
        :form="order.form"
        :labelWidth="120"
        title="确认收货信息"
        :visible="order.visible"
        @hideDialog="order.visible = false"
        @confirm="confirmOrder"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { Confirm } from '@/decorator'
import Sort from './components/sort.vue'

@Component({
  components: {
    Sort
  }
})
export default class Task extends Vue {
  searchForm: any = {
    searchValue: '',
    projectId: undefined,
    status: ''
  };
  form: any = {
    date: [],
    number1: 0,
    number2: 0,
    price1: 0,
    price2: 0
  };

  get filterData () {
    return {
      searchValue: {
        label: '关键词',
        type: 'input',
        template: {
          placeholder: '请输入关键词',
          clearable: true
        }
      },
      projectId: {
        label: '项目筛选',
        type: 'select',
        width: 400,
        template: {
          placeholder: '请选择项目',
          clearable: true,
          filterable: true,
          options: this.projects,
          callback: this.callbackProject,
          popupScroll: this.popupScroll,
          search: this.searchProject
        }
      }
    };
  }
  projects: any = [] // 筛选项目列表
  Data: any = [];
  pageConfig: any = {
    current: 1,
    total: 10,
    pageSize: 10
  };
  currentPage:any = 1
  order: any = {
    rows: {
      // projectName: {
      //   label: '购入单位',
      //   showDisabled: true
      // },
      sendNum: {
        label: '发货数量',
        showDisabled: true
      },
      collectNum: {
        el: 'inputNumber',
        label: '收货数量',
        placeholder: '请输入',
        rules: [{ required: true, message: '请输入收货数量', trigger: 'blur' }]
      },
      sendPrice: {
        label: '发货单价',
        showDisabled: true
      },
      collectPrice: {
        el: 'inputNumber',
        label: '收货单价',
        placeholder: '请输入',
        rules: [{ required: true, message: '请输入收货单价', trigger: 'blur' }]
      }
    },

    form: {
      orderId: '',
      sendNum: '',
      collectNum: '',
      sendPrice: '',
      collectPrice: ''
    },
    visible: false
  }
  searchValue: any = ''
  statusList:any=[
    {
      label: '全部',
      value: ''
    },
    {
      label: '待发货',
      value: 'DFH'
    },
    {
      label: '已发货',
      value: 'YFH'
    },
    {
      label: '已完成',
      value: 'YWC'
    },
    {
      label: '已取消',
      value: 'YQX'
    }
  ]
  switchStatus (val:any) {
    let status
      switch (val) {
	  case 'DFH':
	      status = '待发货'
	      break
	  case 'YFH':
	      status = '已发货'
	      break
	  case 'DSH':
	      status = '待收货'
	      break
	  case 'YSH':
	      status = '已收货'
	      break
	  case 'YWC':
	      status = '已完成'
	      break
	  case 'YQX':
	      status = '已取消'
	      break
	  }
	  return status
  }

  init () {
    this.getList()
    this.getProjects()
  }
  getProjects () {
    let data = {
      page: this.currentPage,
      size: 100,
      searchValue: this.searchValue
    }
    this.$api.projectRoleProjectListFetch(data).then((res: any) => {
      let projects = this.projects.concat(res.data.records.map((item: any) => ({label: item.ncProjectName, value: item.ncProjectId + '-' + item.ncProjectName, pkOrg: item.pkOrg})))
      this.projects = projects
    })
  }
  searchProject (val:any) {
    this.searchValue = val
    this.currentPage = 1
    this.projects = []
    this.getProjects()
  }
  callbackProject (val:any) {
    this.searchValue = val
    this.currentPage = 1
    this.projects = []
    this.getProjects()
  }
  // 滚动选择框时执行
  popupScroll (e:any) {
    const { scrollHeight, scrollTop, clientHeight } = e.target
      if (Math.floor(scrollHeight - scrollTop) === clientHeight) {
        this.currentPage++
        this.getProjects()
      }
  }
  getList () {
    let { searchValue, projectId, status } = this.searchForm;
    let data = {
      type: 'GR',
      page: this.pageConfig.current,
      size: this.pageConfig.pageSize,
      name: searchValue,
      ncProjectId: projectId ? projectId.split('-')[0] : '',
      status: status
    };
    this.$api.orderMyList2Fetch(data).then((res: any) => {
      this.Data = res.data.records;
      this.pageConfig.total = res.data.total;
      if (!this.Data.length && this.pageConfig.current > 1) {
        --this.pageConfig.current;
        this.getList();
      }
    });
  }
  changePage (val: number) {
    this.pageConfig.current = val;
    this.getList();
  }
  searchHandle () {
    this.pageConfig.current = 1;
    this.getList();
  }
  // 删除订单
  delHandle (titleId: any) {
    this.$confirm({
      title: '提示',
      content: '是否删除订单？',
      onOk: () => {
        let data = { titleId, type: 'GR' }
        this.$api.orderDeleteFetch(data).then(() => {
          this.$message.success('删除订单成功')
          this.getList()
        })
      },
      onCancel: () => {}
    })
  }
  // 结束订单
  overHandle (titleId: any) {
    this.$confirm({
      title: '提示',
      content: '是否结束订单？',
      onOk: () => {
        let data = { titleId }
        this.$api.orderFinishFetch(data).then(() => {
          this.$message.success('结束订单成功')
          this.getList()
        })
      },
      onCancel: () => {}
    })
  }
  // changeStatus (row: any, index: number) {
  //   let { adminId, status } = row;
  //   this.$api
  //     .adminStatusFetch({ adminId, status: !status })
  //     .then((res: any) => {
  //       this.$message.success(`${status ? '冻结' : '正常'}成功`);
  //       this.getList();
  //     });
  // }
  showDetail (item: any) {
    this.$router.push({
      path: '/allot/myPurchase/detail',
      query: { orderId: item.orderId, _alias: 'detail' }
    });
  }
  // 筛选
  changeSort (type: any, value: number) {
    this.pageConfig.current = 1;
  }
  // 取消预定
  @Confirm('是否取消预定？')
  cancelHandle (titleId: string) {
    this.$api.orderCancelFetch({ titleId }).then((res: any) => {
      this.$message.success('取消预定成功')
      this.getList()
    })
  }
  showConfirmDialog ({ orderId, sendNum, sendPrice, ncProjectName }: any) {
    this.order.form = Object.assign({}, this.order.form, {
      orderId,
      sendNum,
      sendPrice,
      ncProjectName
    })
    this.order.visible = true
  }
  confirmOrder () {
    const { orderId: order_id, collectNum: collect_num, collectPrice: collect_price } = this.order.form
    this.$api.orderHadReceiveFetch({
      collect_num,
      collect_price,
      order_id
    }).then((res: any) => {
      this.$message.success('确认收货成功')
      this.order.visible = false
      this.getList()
    })
  }
}
</script>

<style lang="scss">
#Shelf {
  .filter-box {
    margin-bottom: 0;
  }
  .ant-tabs-bar {
    margin: 0;
    border-bottom: none;
  }
  .item-btn{
    text-align: right;
    .btns{
      margin-right: 15px;
    }
  }
  .table-header{
    text-align: center;
  }
  .item-col{
    text-align: center;
  }
  .search{
    display: flex;
    align-items: center;
    .search-selsect{
      width: 150px;
    }
  }
}
</style>
